<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElRow, ElCol, ElButton, ElDialog, ElMessage, ElTooltip } from 'element-plus'
import { Plus, Refresh, Monitor } from '@element-plus/icons-vue'
import { useDevicesStore } from '@/stores/devices'
import DeviceCard from '@/components/DeviceCard/index.vue'
import StatusCard from '@/components/StatusCard/index.vue'
import type { Device } from '@/types'

const devicesStore = useDevicesStore()
const showAddDialog = ref(false)
const showConnectDialog = ref(false)
const isScanning = ref(false)
const adbManagerInitialized = ref(false)
const connectIpAddress = ref('')
const connectPort = ref('5555')

const devices = computed(() => devicesStore.devices)
const deviceStats = computed(() => ({
  total: devicesStore.deviceCount,
  online: devicesStore.onlineDeviceCount,
  offline: devicesStore.offlineDeviceCount,
  busy: devicesStore.busyDeviceCount
}))

onMounted(async() => {
  await initializeAndLoadDevices()
})

const initializeAndLoadDevices = async() => {
  try {
    // 先加载数据库中的设备
    await devicesStore.fetchDevices()
    
    // 尝试初始化ADB设备管理器
    try {
      await devicesStore.initializeDeviceManager()
      adbManagerInitialized.value = true
      ElMessage.success('ADB设备管理器初始化成功')
      
      // 扫描ADB设备
      await scanDevices()
    } catch (adbError: any) {
      // ADB初始化失败
      if (adbError.toString().includes('ADB not found')) {
        ElMessage.error('ADB设备管理器初始化失败：无法启动ADB服务')
        console.error('ADB initialization failed:', adbError)
      } else {
        ElMessage.error('ADB设备管理器初始化失败: ' + adbError)
      }
      console.error('ADB initialization failed:', adbError)
      // 即使ADB失败，应用仍可继续运行
    }
  } catch (error) {
    ElMessage.error('加载设备列表失败')
    console.error('Failed to load devices:', error)
  }
}


const scanDevices = async() => {
  if (!adbManagerInitialized.value) {
    ElMessage.warning('设备管理器未初始化')
    return
  }
  
  isScanning.value = true
  try {
    const adbDevices = await devicesStore.scanAdbDevices()
    ElMessage.success(`扫描完成，发现 ${adbDevices.length} 个ADB设备`)
  } catch (error) {
    ElMessage.error('设备扫描失败')
    console.error('Device scan failed:', error)
  } finally {
    isScanning.value = false
  }
}

const handleConnect = async(device: Device) => {
  try {
    // 优先使用ADB连接
    if (device.platform === 'android' && adbManagerInitialized.value) {
      await devicesStore.connectAdbDevice(device.id)
    } else {
      await devicesStore.connectDevice(device.id)
    }
    ElMessage.success(`设备 ${device.name} 连接成功`)
  } catch (error) {
    ElMessage.error(`设备连接失败: ${error}`)
  }
}

const handleDisconnect = async(device: Device) => {
  try {
    // 优先使用ADB断开
    if (device.platform === 'android' && adbManagerInitialized.value) {
      await devicesStore.disconnectAdbDevice(device.id)
    } else {
      await devicesStore.disconnectDevice(device.id)
    }
    ElMessage.success(`设备 ${device.name} 断开连接`)
  } catch (error) {
    ElMessage.error(`设备断开失败: ${error}`)
  }
}

const handleControl = async(device: Device) => {
  try {
    ElMessage.info(`正在启动设备 ${device.name} 的控制界面...`)
    // TODO: 实现设备控制界面
  } catch (error) {
    ElMessage.error(`启动设备控制失败: ${error}`)
  }
}

const handleScreenshot = async(device: Device) => {
  try {
    if (device.platform === 'android' && adbManagerInitialized.value) {
      await devicesStore.getDeviceScreenshot(device.id)
      ElMessage.success('截图获取成功')
      // TODO: 显示截图预览
    } else {
      ElMessage.warning('截图功能仅支持Android设备')
    }
  } catch (error) {
    ElMessage.error(`获取截图失败: ${error}`)
  }
}

const handlePerformance = async(device: Device) => {
  try {
    if (device.platform === 'android' && adbManagerInitialized.value) {
      const performance = await devicesStore.getDevicePerformance(device.id)
      ElMessage.success('性能数据获取成功')
      console.log('Device performance:', performance)
      // TODO: 显示性能监控面板
    } else {
      ElMessage.warning('性能监控仅支持Android设备')
    }
  } catch (error) {
    ElMessage.error(`获取性能数据失败: ${error}`)
  }
}

const handleSettings = (device: Device) => {
  ElMessage.info(`打开设备 ${device.name} 设置`)
}

const handleAddDevice = () => {
  showAddDialog.value = true
}

const handleConnectByIp = () => {
  showConnectDialog.value = true
}

const connectDeviceByIp = async() => {
  if (!connectIpAddress.value) {
    ElMessage.warning('请输入设备IP地址')
    return
  }
  
  const address = connectPort.value ? 
    `${connectIpAddress.value}:${connectPort.value}` : 
    connectIpAddress.value
  
  try {
    await devicesStore.connectAdbDevice(address)
    ElMessage.success(`成功连接到设备: ${address}`)
    showConnectDialog.value = false
    connectIpAddress.value = ''
    
    // 连接后自动扫描设备
    setTimeout(async() => {
      await scanDevices()
    }, 500)
  } catch (error: any) {
    ElMessage.error(`连接失败: ${error.message || error}`)
  }
}
</script>

<template>
  <div class="devices-page">
    <div class="page-header">
      <div class="header-left">
        <h2>设备管理</h2>
        <ElTooltip content="ADB设备管理器状态" placement="bottom">
          <div class="adb-status">
            <Monitor :style="{ color: adbManagerInitialized ? '#67c23a' : '#f56c6c' }" />
            <span class="status-text">{{ adbManagerInitialized ? 'ADB已就绪' : 'ADB未连接' }}</span>
          </div>
        </ElTooltip>
      </div>
      <div class="header-actions">
        <ElTooltip content="扫描ADB设备" placement="bottom">
          <ElButton 
            :icon="Refresh" 
            :loading="isScanning"
            :disabled="!adbManagerInitialized"
            @click="scanDevices"
          >
            {{ isScanning ? '扫描中...' : '扫描设备' }}
          </ElButton>
        </ElTooltip>
        <ElButton :icon="Plus" @click="handleConnectByIp">
          通过IP连接
        </ElButton>
        <ElButton type="primary" :icon="Plus" @click="handleAddDevice">
          添加设备
        </ElButton>
      </div>
    </div>

    <!-- 设备统计 -->
    <ElRow :gutter="20" class="stats-row">
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="设备总数"
          :value="deviceStats.total"
          color="#409eff"
          :icon="null"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="在线设备"
          :value="deviceStats.online"
          color="#67c23a"
          trend="up"
          :trend-value="`${Math.round((deviceStats.online / Math.max(deviceStats.total, 1)) * 100)}%`"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="忙碌设备"
          :value="deviceStats.busy"
          color="#e6a23c"
          trend="neutral"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="离线设备"
          :value="deviceStats.offline"
          color="#f56c6c"
          trend="down"
        />
      </ElCol>
    </ElRow>

    <!-- 设备列表 -->
    <div class="devices-grid">
      <ElRow :gutter="20">
        <ElCol
          v-for="device in devices"
          :key="device.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          class="device-col"
        >
          <DeviceCard
            :device="device"
            @connect="handleConnect"
            @disconnect="handleDisconnect"
            @control="handleControl"
            @settings="handleSettings"
            @screenshot="handleScreenshot"
            @performance="handlePerformance"
          />
        </ElCol>
      </ElRow>
    </div>

    <!-- 添加设备对话框 -->
    <ElDialog
      v-model="showAddDialog"
      title="添加设备"
      width="600px"
      :before-close="() => showAddDialog = false"
    >
      <div class="add-device-form">
        <p>设备添加功能正在开发中...</p>
        <p>支持的设备类型：</p>
        <ul>
          <li>Android 真机 (ADB 连接)</li>
          <li>iOS 设备 (WebDriverAgent)</li>
          <li>Android 模拟器</li>
          <li>云手机平台</li>
        </ul>
      </div>
      
      <template #footer>
        <ElButton @click="showAddDialog = false">取消</ElButton>
        <ElButton type="primary" @click="showAddDialog = false">确定</ElButton>
      </template>
    </ElDialog>
    
    <!-- IP连接对话框 -->
    <ElDialog 
      v-model="showConnectDialog" 
      title="通过IP连接设备" 
      width="500px"
    >
      <div class="connect-dialog-content">
        <p class="tips">请确保设备已开启无线调试功能，并与电脑在同一网络中。</p>
        
        <div class="connection-steps">
          <h4>Android设备开启无线调试：</h4>
          <ol>
            <li>在设备上开启开发者选项</li>
            <li>进入"开发者选项" → "无线调试"</li>
            <li>开启"无线调试"开关</li>
            <li>点击"使用配对码配对设备"（首次连接）</li>
            <li>记录显示的IP地址和端口号</li>
          </ol>
        </div>
        
        <el-form :model="{ ip: connectIpAddress, port: connectPort }" label-width="80px">
          <el-form-item label="IP地址" required>
            <el-input 
              v-model="connectIpAddress" 
              placeholder="例如: 192.168.1.100"
              clearable
            />
          </el-form-item>
          <el-form-item label="端口号">
            <el-input 
              v-model="connectPort" 
              placeholder="默认: 5555"
              clearable
            />
          </el-form-item>
        </el-form>
        
        <el-alert type="info" :closable="false">
          <template #default>
            <div>
              <p style="margin: 0;">常见端口说明：</p>
              <ul style="margin: 5px 0 0 20px; padding: 0;">
                <li>5555 - 默认ADB调试端口</li>
                <li>其他端口 - 查看设备"无线调试"界面显示的端口</li>
              </ul>
            </div>
          </template>
        </el-alert>
      </div>
      
      <template #footer>
        <ElButton @click="showConnectDialog = false">取消</ElButton>
        <ElButton type="primary" @click="connectDeviceByIp">连接</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped lang="scss">
.devices-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      h2 {
        margin: 0;
        color: var(--el-text-color-primary);
      }
      
      .adb-status {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 4px 8px;
        border-radius: 4px;
        background-color: var(--el-fill-color-light);
        
        .status-text {
          font-size: 12px;
          color: var(--el-text-color-regular);
        }
      }
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .stats-row {
    margin-bottom: 24px;
  }
  
  .devices-grid {
    .device-col {
      margin-bottom: 20px;
    }
  }
  
  .add-device-form {
    padding: 20px 0;
    
    ul {
      margin: 16px 0;
      padding-left: 24px;
      
      li {
        margin-bottom: 8px;
        color: var(--el-text-color-regular);
      }
    }
  }
  
  .connect-dialog-content {
    .tips {
      color: var(--el-text-color-regular);
      margin-bottom: 20px;
    }
    
    .connection-steps {
      background: var(--el-fill-color-light);
      padding: 16px;
      border-radius: 8px;
      margin-bottom: 24px;
      
      h4 {
        margin: 0 0 12px 0;
        color: var(--el-text-color-primary);
        font-size: 14px;
      }
      
      ol {
        margin: 0;
        padding-left: 20px;
        
        li {
          color: var(--el-text-color-regular);
          line-height: 1.8;
          font-size: 13px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .devices-page {
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;
      
      h2 {
        text-align: center;
      }
    }
  }
}
</style>